package com.kly.pay.eventbus;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.DeadEvent;
import com.google.common.eventbus.Subscribe;
import com.kly.enums.PayLogActionEnum;
import com.kly.pay.db.dao.PPayLogDao;
import com.kly.pay.db.entity.PPayLogEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * EventBus 监听器
 * @author linqu
 */
@Component
@Slf4j
public class EventListener {

    @Resource
    AsyncEventBus asyncEventBus;
    @Resource
    PPayLogDao pPayLogDao;

    /**
     * 订阅者注册到EventBus
     */
    @PostConstruct
    public void init() {
        asyncEventBus.register(this);
    }

    /**
     * 接收到指定事件后的处理
     * @param event
     */
    @Subscribe
    public void doLog(Event event) {
//        log.info("doLogBeginning: {}", event.getContent());
        try {
            final PayLogActionEnum payLogActionEnum = event.getPayLogActionEnum();
            PPayLogEntity entity = new PPayLogEntity();
            entity.setType(payLogActionEnum.getName());
            entity.setPayOrderNo(event.getOrderNo());
            entity.setReqParams(event.getContent());
            pPayLogDao.insert(entity);
        } catch (Exception e) {
            log.info("doLogError: {}", event.getContent(), e);
        }
//        log.info("doLogEnded: {}", event.getContent());
    }

    /**
     * 接收没有订阅者的消息
     * @param event
     */
    @Subscribe
    public void handle(DeadEvent event){
        // 事件无法处理, 只记录日志
        log.error("The event un-subscribe yet, event ：{}",event);
    }
}
